﻿using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using MkLink;

namespace SymbolicLinkManageCore
{
    [Serializable]
    public class HardLinkData : INotifyPropertyChanged, IEquatable<HardLinkData>
    {
        public event PropertyChangedEventHandler? PropertyChanged;
        private void SendNotify(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        private string _FilePath = string.Empty;
       
        [XmlAttribute] public string FilePath
        {
            get => _FilePath; set
            {
                if (_FilePath.Equals(value, StringComparison.OrdinalIgnoreCase))
                    return;
                _FilePath = value;
                _IsValid = true;
                SendNotify(nameof(FilePath));
                SendNotify(nameof(IsFileExists));
                SendNotify(nameof(IsValid));
            }
        }
        [XmlIgnore] public bool IsFileExists => File.Exists(FilePath);
        
        private bool _IsValid = true;
        [XmlIgnore] public bool IsValid => _IsValid && IsFileExists;

        [XmlIgnore] public uint LinkCount => MkLinkTools.GetFileLinkCount(FilePath);
        public HardLinkData() { }
        public HardLinkData(string FilePath) { this.FilePath = FilePath; }

        
        public void SetValid(bool value) { if (_IsValid == value) return; _IsValid = value; SendNotify(nameof(IsValid)); }
        public void Valid(string[] ValidGroupPaths)
        {
            if(!File.Exists(FilePath))
            {
                SetValid(false);
                return;
            }
            if (ValidGroupPaths.Contains(FilePath, StringComparer.OrdinalIgnoreCase))
                SetValid(true);
            else SetValid(false);
        }

        public bool Equals(HardLinkData? other) => other?.FilePath.Equals(this.FilePath, StringComparison.OrdinalIgnoreCase) ?? false;

        public override bool Equals(object? obj) => obj == null ? false : Equals((HardLinkData)obj);

        public override int GetHashCode() => _FilePath.GetHashCode(StringComparison.OrdinalIgnoreCase);

        public override string ToString() => _FilePath;

        public static implicit operator string(HardLinkData data) => data.ToString();
        public static explicit operator HardLinkData(string Path) => new HardLinkData(Path);
    }
}
